﻿using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using SangsTools;
using System.Threading.Tasks;

namespace UI
{
    public class UIPopUpWindow : IPoolMember
    {
        public STPopUpWindowData UIData { get; private set; }
        private IPopUpWindowEventHandler _eventHandler;
        private Transform _tfRoot;

        public Text TitleText { get; private set; }
        public Text DesText { get; private set; }
        private Transform _tfOptionRoot;
        private Button[] arrOptionBtn;

        private UIPopUpWindow(Transform tfRoot)
        {
            if (tfRoot == null)
                throw new System.Exception();

            _tfRoot = tfRoot;
            _tfRoot.localScale = Vector3.zero;

            TitleText = tfRoot.Find("TitleText").GetComponent<Text>();
            DesText = tfRoot.Find("DesScrollView/Viewport/Content").GetComponent<Text>();
            _tfOptionRoot = tfRoot.Find("BtnRoot");
        }
        private UIPopUpWindow Init(STPopUpWindowData data, IPopUpWindowEventHandler eventHandler)
        {
            // if (data.arrOptions == null || data.arrOptions.Length == 0)
            // {
            //     //TODO 加个默认的exitBtn就可以了
            //     throw new System.Exception("弹出UI没给选项");
            // }

            UIData = data;
            _eventHandler = eventHandler;
            RefreshUI();
            Show();
            return this;
        }

        private void RefreshUI()
        {
            TitleText.text = UIData.strTitle;
#if UNITY_EDITOR
            TitleText.text = $"{UIData.strTitle} - {UIData.strTag}";
#endif

            DesText.text = UIData.strDes;

            if (UIData.arrOptions != null)
            {
                arrOptionBtn = new Button[UIData.arrOptions.Length];
                for (var i = 0; i < UIData.arrOptions.Length; i++)
                {
                    arrOptionBtn[i] = _poolOptionBtn.GetMember();
                    arrOptionBtn[i].transform.SetParent(_tfOptionRoot);
                    arrOptionBtn[i].transform.localScale = Vector3.one;

                    arrOptionBtn[i].GetComponentInChildren<Text>().text = UIData.arrOptions[i];
                    int index = i;

                    arrOptionBtn[i].onClick.RemoveAllListeners();
                    arrOptionBtn[i].onClick.AddListener(() => OnClickOptionAsync(index));
                }
            }
        }

        private async void OnClickOptionAsync(int index)
        {
            await HideAsync();
            var tmp = _eventHandler;
            _eventHandler = null;
            tmp?.OnChooseOption(index, UIData);
        }

        private void Show()
        {
            _tfRoot.gameObject.SetActive(true);
            _tfRoot.transform.DOKill();
            _tfRoot.transform.DOScale(1, 0.2f).SetEase(Ease.OutBack);
        }
        public async Task HideAsync()
        {
            _tfRoot.transform.DOKill();
            _tfRoot.transform.DOScale(0, 0.2f);

            await Task.Delay(200);

            _poolUI.Recycle(this);
        }

        #region 内存池接口
        void IPoolMember.OnCreate()
        { }

        void IPoolMember.OnGet()
        {
            _tfRoot.gameObject.SetActive(true);
            _tfRoot.localScale = Vector3.zero;
            _tfRoot.localPosition = Vector3.zero;
        }

        void IPoolMember.OnRecycle()
        {
            _tfRoot.gameObject.SetActive(false);
            SetNull();
        }

        void IPoolMember.OnDestroy()
        {
            if (_tfRoot != null)
                MonoBehaviour.Destroy(_tfRoot.gameObject);

            SetNull();
            _eventHandler = null;
        }

        private void SetNull()
        {
            if (arrOptionBtn != null)
            {
                for (var i = 0; i < arrOptionBtn.Length; i++)
                {
                    _poolOptionBtn.Recycle(arrOptionBtn[i]);
                }
                arrOptionBtn = null;
            }
        }
        #endregion

        #region 静态方法
        private class UIPool : PoolBase<UIPopUpWindow>
        {
            protected override UIPopUpWindow CreateMember()
            {
                Transform tfUI = MonoBehaviour.Instantiate(_uiPrefab).transform;
                tfUI.SetParent(_tfUIRoot.transform);
                tfUI.localPosition = Vector3.zero;
                return new UIPopUpWindow(tfUI);
            }
        }

        //弹窗UI的canvas的gameObj
        private static GameObject _tfUIRoot;
        //弹窗UI的预制
        private static GameObject _uiPrefab;
        //UI脚本的内存池
        private static UIPool _poolUI;
        //选项按钮的内存池
        private static IPool<Button> _poolOptionBtn;

        //静态构造函数不能用resource，只能这样初始化了
        private static void InitPool()
        {
            if (_poolUI != null) return;

            _tfUIRoot = MonoBehaviour.Instantiate<GameObject>(Resources.Load<GameObject>("UI/PopUpWindowCanvas"));
            MonoBehaviour.DontDestroyOnLoad(_tfUIRoot);

            _uiPrefab = _tfUIRoot.transform.Find("PopUpWindowPrefab").gameObject;
            _uiPrefab.gameObject.SetActive(false);

            _poolOptionBtn = new PoolComponent<Button>(Resources.Load<Button>("UI/PopUpWindowOptionBtn"));

            _poolUI = new UIPool();
        }

        public static UIPopUpWindow ShowPopUpWindow(STPopUpWindowData data, IPopUpWindowEventHandler eventHandler)
        {
            InitPool();
            return _poolUI.GetMember().Init(data, eventHandler);
        }
        #endregion
    }
}